<template>
  <div class="list-common-table">
    <t-form
      ref="form"
      :data="formDataQueryRecord"
      :label-width="80"
      colon
      @reset="onReset"
      @submit="onSubmit"
      :style="{ marginBottom: '20px' }"
    >
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[24, 24]">
            <t-col :flex="1">
              <t-form-item label="测试计划" name="name">
                <t-select-input
                  v-model="selectValue"
                  :popup-visible="popupVisible"
                  :popup-props="{ overlayInnerStyle: { padding: '6px' } }"
                  placeholder="请输入测试计划关键字"
                  allow-input
                  clearable
                  @input-change="onInputChange"
                  @popup-visible-change="onPopupVisibleChange"
                >
                  <template #panel>
                    <ul class="tdesign-demo__select-input-ul-autocomplete">
                      <li v-for="item in filteredOptions" :key="item.value" @click="() => onOptionClick(item)">
                        {{ item.label }}
                      </li>
                    </ul>
                  </template>
                  <template #suffixIcon>
                    <SearchIcon/>
                  </template>
                </t-select-input>
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="执行状态" name="status">
                <t-select
                  v-model="formDataQueryRecord.status"
                  class="form-item-content`"
                  :options="RECORD_STATUS_OPTIONS"
                  placeholder="请选择执行状态"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="执行人" name="user">
                <t-select
                  v-model="formDataQueryRecord.user"
                  class="form-item-content`"
                  @focus="loadUserList"
                  placeholder="请选择执行人"
                  @input="handleUserSelect"
                >
                  <t-option
                    v-for="item in options2"
                    :value="item.value"
                    :label="item.label"
                    :key="item.value"
                  ></t-option>
                </t-select>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }"> 查询</t-button>
          <t-button type="reset" variant="base" theme="default"> 重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <div class="table-container">
      <t-table
        :data="data"
        :columns="columns"
        :rowKey="rowKey"
        :verticalAlign="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        :loading="dataLoading"
        :headerAffixedTop="true"
        :headerAffixProps="{ offsetTop, container: getContainer }"
      >
        <template #pass_status="{ row }">
          <t-tag v-if="row.pass_status === RECORD_STATUS.FAIL" theme="danger" variant="light">执行失败</t-tag>
          <t-tag v-if="row.pass_status === RECORD_STATUS.INIT" theme="warning" variant="light">未执行</t-tag>
          <t-tag v-if="row.pass_status === RECORD_STATUS.PENDING" theme="warning" variant="light">执行中</t-tag>
          <t-tag v-if="row.pass_status === RECORD_STATUS.SUCCESS" theme="success" variant="light">执行成功</t-tag>
        </template>
        <template #pass_rate="{ row }">
          <div style="width:100px">
            <t-progress :percentage="row.pass_rate"/>
          </div>
        </template>
        <template #op="slotProps">
          <a class="t-button-link" @click="rehandleClickQuery((slotProps.row))">查看</a>
          <a class="t-button-link" @click="handleClickDelete(slotProps)">执行</a>
        </template>
      </t-table>
      <!--      <t-dialog-->
      <!--        header="确认删除当前所选合同？"-->
      <!--        :body="confirmBody"-->
      <!--        :visible.sync="confirmVisible"-->
      <!--        @confirm="onConfirmDelete"-->
      <!--        :onCancel="onCancel"-->
      <!--      >-->
      <!--      </t-dialog>-->
    </div>
  </div>
</template>
<script>
import {prefix} from '@/config/global';
import Trend from '@/components/trend/index.vue';
import {
  RECORD_STATUS,
  RECORD_STATUS_OPTIONS,
} from '@/constants';
import {SearchIcon} from 'tdesign-icons-vue';

export default {
  name: 'list-table',
  components: {
    Trend,
    SearchIcon,
  },
  data() {
    return {
      selectValue: '',
      popupVisible: false,
      recordOptions: [],
      RECORD_STATUS,
      RECORD_STATUS_OPTIONS,
      prefix,
      formDataQueryRecord: {
        testplanId: '',
        status: '',
        user: '',
      },
      options2:[],
      data: [],
      dataLoading: false,
      value: 'first',
      columns: [
        {
          title: 'ID',
          fixed: 'left',
          width: 50,
          align: 'left',
          ellipsis: true,
          colKey: 'id',
        },
        {
          title: '记录名称',
          width: 100,
          ellipsis: true,
          colKey: 'name',
        },
        {
          title: '测试计划',
          width: 150,
          ellipsis: true,
          colKey: 'testplan_name',
        },
        {title: '执行状态', colKey: 'pass_status', width: 100, cell: {col: 'pass_status'}},
        {
          title: '通过率',
          width: 150,
          ellipsis: true,
          colKey: 'pass_rate',
        },
        {
          title: '创建人',
          width: 100,
          ellipsis: true,
          colKey: 'create_user',
        },
        {
          title: '创建时间',
          width: 150,
          ellipsis: true,
          colKey: 'create_time',
        },
        {
          title: '开始执行时间',
          width: 150,
          ellipsis: true,
          colKey: 'start_time',
        },
        {
          title: '结束执行时间',
          width: 150,
          ellipsis: true,
          colKey: 'end_time',
        },
        {
          align: 'left',
          fixed: 'right',
          width: 200,
          colKey: 'op',
          title: '操作',
        },
      ],
      rowKey: 'index',
      tableLayout: 'auto',
      verticalAlign: 'top',
      bordered: true,
      hover: true,
      rowClassName: (rowKey) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 100,
        defaultCurrent: 1,
      },
      confirmVisible: false,
      deleteIdx: -1,
    };
  },
  computed: {
    filteredOptions() {
      if (this.selectValue) {
        const keyword = this.selectValue.toLowerCase();
        return this.recordOptions.filter((item) =>
          item.label.toLowerCase().includes(keyword)
        );
      }
      return this.recordOptions;
    },

    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },

  },
  mounted() {
    this.dataLoading = true;
    this.$request
      .get('/api/query/record_list')
      .then((res) => {
        if (res.data.code === '000') {
          this.data = res.data.data;
          const testplanIds = [...new Set(this.data.map((record) => record.testplan_id))];
          this.recordOptions = testplanIds.map((testplanId) => {
            const testplanName = this.data.find((record) => record.testplan_id === testplanId).testplan_name;
            return {
              label: testplanName,
              value: testplanId,
            };
          });
          console.log("拿到的筛选数据~~~~~~~", JSON.stringify(this.recordOptions))
          console.log("拿到数据进行赋值", JSON.stringify(this.data))
          this.pagination = {
            ...this.pagination,
            total: this.data.length,
          };
        }
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        this.dataLoading = false;
      });
  },
  methods: {
    getContainer() {
      return document.querySelector('.tdesign-starter-layout');
    },
    onReset(data) {
      console.log(data);
      this.formDataQueryRecord = {
        testplanId: '',
        status: 0,
        user: ''
      };
      window.location.reload(); // 刷新页面
    },
    // onSubmit(data) {
    //   const testplanId = formData.testplanId;
    // },
    loadUserList() {
      this.$request
        .get('/api/user/query/user_list')
        .then((res) => {
          console.log("用户列表~~~~~", res.data)
          if (res.data.code === '000') {
            const transformedData = res.data.data.map((item) => ({
              value: item.id,
              label: item.username,
            }));
            this.options2 = transformedData
            console.log('筛选条件中的用户列表~~~~~~~~',this.options2)
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    onSubmit({validateResult, firstError}) {
      console.log("validateResult~~~", validateResult)
      if (validateResult === true) {
        this.dataLoading = true;

        // 构建筛选参数
        // const params = {
        //   testplan_id: this.formDataQueryRecord.testplanId,
        //   pass_status: this.formDataQueryRecord.status,
        //   user: this.formDataQueryRecord.user
        // };
        // 构建筛选参数
        const params = {};

        if (this.formDataQueryRecord.testplanId) {
          params.testplan_id = this.formDataQueryRecord.testplanId;
        }

        if (this.formDataQueryRecord.status !== '' && this.formDataQueryRecord.status !== null) {
          params.pass_status = this.formDataQueryRecord.status;
        }

        if (this.formDataQueryRecord.user) {
          params.user = this.formDataQueryRecord.user;
        }

        // 发起请求，获取筛选结果
        this.$request
          .get('/api/query/record_list', {params})
          .then((res) => {
            if (res.data.code === '000') {
              this.data = res.data.data;
              console.log("这是二次筛选以后得")
              this.pagination = {
                ...this.pagination,
                total: this.data.length
              };
            }
            this.$message.success('提交成功');
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => {
            this.dataLoading = false;
          });
      } else {
        console.log('Errors: ', validateResult);
        this.$message.warning(firstError);
      }
    },
    rehandlePageChange(curr, pageInfo) {
      console.log('分页变化', curr, pageInfo);
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log('统一Change', changeParams, triggerAndData);
    },
    rehandleClickQuery(row) {
      const recordId = row.id
      console.log("recordId~~~~~~", recordId)
      this.$router.push({ name: 'FunctionOfTestreportDetail', query: { id: recordId } });
    },
    handleClickDelete(row) {
      this.deleteIdx = row.rowIndex;
      this.confirmVisible = true;
    },
    onConfirmDelete() {
      // 真实业务请发起请求
      this.data.splice(this.deleteIdx, 1);
      this.pagination.total = this.data.length;
      this.confirmVisible = false;
      this.$message.success('删除成功');
      this.resetIdx();
    },
    onCancel() {
      this.resetIdx();
    },
    resetIdx() {
      this.deleteIdx = -1;
    },
    //下拉菜单模糊搜索
    onOptionClick(item) {
      this.selectValue = item.label;
      this.formDataQueryRecord.testplanId = item.value; // 更新testplanId的值
      this.popupVisible = false;
    },
    onInputChange(keyword) {
      this.selectValue = keyword;
    },
    onPopupVisibleChange(val) {
      this.popupVisible = val;
    },
    handleUserSelect(selectedValue) {
      const selectedOption = this.options2.find(item => item.value === selectedValue);
      if (selectedOption) {
        this.formDataQueryRecord.user = selectedOption.label;
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: 30px 32px;
  border-radius: var(--td-radius-default);
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}

.t-button + .t-button {
  margin-left: var(--td-comp-margin-s);
}

.tdesign-demo__select-input-ul-autocomplete {
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.tdesign-demo__select-input-ul-autocomplete > li {
  display: block;
  border-radius: 3px;
  line-height: 22px;
  cursor: pointer;
  padding: 3px 8px;
  color: var(--td-text-color-primary);
  transition: background-color 0.2s linear;
  white-space: nowrap;
  word-wrap: normal;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tdesign-demo__select-input-ul-autocomplete > li:hover {
  background-color: var(--td-bg-color-container-hover);
}
</style>
